﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using HCDV;
using HCDV.HCSP;
using hrainwebbase.basecs;
using hrainwebbase.business;
using hrainwebbase.ashx.CallBusiness;
using Newtonsoft.Json;
using hrainwebbase.ashx.spfunction;

namespace hrainwebbase.ashx
{

    /// <summary>
    /// sp 的摘要说明
    /// </summary>
    public class spopen : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        //用户ID，用户机构ID，用户编号，用户机构编号，用户角色编号
        /// <summary>
        /// 回调动作代码
        /// </summary>
        protected string callBackAction
        {
            get
            {
                if (GetParam("action") == null)
                    return string.Empty;
                else
                    return GetParam("action");
            }
        }
        public enum RequestType
        {
            Auto,
            Form,
            QueryString,
            Cookies
        }
        protected string GetParam(string name, RequestType requestType = RequestType.Auto)
        {
            if ((requestType == RequestType.Auto || requestType == RequestType.Form) && !string.IsNullOrEmpty(Mcontext.Request.Form[name]))
                return Mcontext.Request.Form[name];
            if ((requestType == RequestType.Auto || requestType == RequestType.QueryString) && !string.IsNullOrEmpty(Mcontext.Request.QueryString[name]))
                return Mcontext.Request.QueryString[name];
            if ((requestType == RequestType.Auto || requestType == RequestType.Cookies) && Mcontext.Request.Cookies[name] != null)
                return Mcontext.Request.Cookies[name].Value;
            return string.Empty;
        }
        protected HttpContext Mcontext;
        public void ProcessRequest(HttpContext context)
        {

            Mcontext = context;
            Mcontext.Response.ContentType = "application/Json";
       
            switch (callBackAction)
            {
                #region 通用查询
                case JsonControl.Select:
                    {

                        try
                        {
                            int totalCount = 0;
                            string orderType = GetParam("order");
                            string sortfeild = GetParam("sort");
                            string page = GetParam("start");
                            if (!string.IsNullOrEmpty(GetParam("hcrainallrow")))//总记录数
                            {
                                totalCount = int.Parse(GetParam("hcrainallrow"));
                            }
                            int ipage = 0;
                            int irows = 100;
                            if (!string.IsNullOrEmpty(page))
                            {
                                irows = int.Parse(GetParam("length"));
                                ipage = int.Parse(GetParam("start"));
                                ipage = (ipage) / irows + 1;
                            }
                            string tableinfo = GetParam("tableinfo");
                            string refields = GetParam("refields");
                            //string dfdf = GetParam("finddename");
                            string wheresp = GetParam("wheresp");
                            string sporderby = GetParam("sporderby");
                            string whereadd = "  1=1 ";
                            string subinfo = GetParam("subinfo");//子查询info
                            if (!string.IsNullOrEmpty(wheresp))
                            { whereadd += wheresp; }
                            string wherespadd = GetParam("wherespadd");
                            if (!string.IsNullOrEmpty(wherespadd))
                            { whereadd += wherespadd; }
                            //查询条件
                            HttpRequest Request = Mcontext.Request;
                            string fieldinfo = "";
                            string fieldvalue = "";
                            for (int i = 0; i < Request.Form.Count; i++)
                            {

                                if (Request.Form.Keys[i].ToString().StartsWith("find") && Request.Form[i].ToString().Trim().Length > 0)
                                {
                                    fieldinfo = Request.Form.Keys[i].ToString().Replace("find", "");
                                    fieldvalue = ObjIUD.sqlfieldc(Request.Form[i].ToString());
                                    if (fieldinfo.EndsWith("_l"))
                                    { whereadd += " and " + fieldinfo.Replace("_l", "") + " like '%" + fieldvalue + "%'"; }
                                    else if (fieldinfo.EndsWith("_d"))
                                    { whereadd += " and " + fieldinfo.Replace("_d", "") + " = '" + fieldvalue + "'"; }
                                    else if (fieldinfo.EndsWith("_time"))
                                    {
                                        whereadd += " and " + fieldinfo.Replace("_time", "") + " = '" + fieldvalue + "'";
                                    }
                                    else if (fieldinfo.EndsWith("_times"))
                                    {
                                        whereadd += " and " + fieldinfo.Replace("_times", "") + " >= '" + fieldvalue + "'";
                                    }
                                    else if (fieldinfo.EndsWith("_timee"))
                                    {
                                        whereadd += " and " + fieldinfo.Replace("_timee", "") + " <= '" + fieldvalue + "'";
                                    }
                                    else
                                    {
                                        whereadd += " and " + fieldinfo + " like '%" + fieldvalue + "%'";
                                    }

                                }
                            }

                            {
                                string oc = GetParam("order[0][column]");
                                string od = GetParam("order[0][dir]");
                                if (!string.IsNullOrEmpty(oc))
                                {
                                    if (!string.IsNullOrEmpty(GetParam("columns[" + oc + "][data]")))
                                    {
                                        if (string.IsNullOrEmpty(sporderby))
                                        {
                                            sporderby = " " + GetParam("columns[" + oc + "][data]") + " " + (string.IsNullOrEmpty(od) ? "" : od);
                                        }
                                        else
                                        {
                                            sporderby = " " + sporderby + "," + GetParam("columns[" + oc + "][data]") + " " + (string.IsNullOrEmpty(od) ? "" : od);
                                        }
                                    }
                                }
                            }

                            DataTable dt = null;
                            using (dbsimple db = new dbsimple())
                            {
                                if (ipage != 0)
                                {
                                    if (irows == -1)
                                    {
                                        irows = 1000;
                                    }
                                    dt = db.getReportPage(tableinfo, refields, ipage, irows, whereadd, string.IsNullOrEmpty(sporderby) ? null : sporderby, ref totalCount);
                                }
                                else
                                {
                                    dt = db.getReportNoPage(tableinfo, refields, whereadd, string.IsNullOrEmpty(sporderby) ? null : sporderby);
                                }
                            }
                            string re = "";
                            StringBuilder jsonStr = new StringBuilder();
                            jsonStr.Append("{\"sEcho\":\"");
                            jsonStr.Append(GetParam("sEcho"));
                            jsonStr.Append("\",\"iTotalRecords\":\"");
                            jsonStr.Append(totalCount);
                            jsonStr.Append("\",\"iTotalDisplayRecords\":\"");
                            jsonStr.Append(totalCount);
                            jsonStr.Append("\",\"data\":");
                            if (dt.Rows.Count == 0)
                                jsonStr.Append("[]");
                            else
                                jsonStr.Append(JsonControl.GetJsonStr(dt, subinfo));
                            jsonStr.Append("}");

                            re = jsonStr.ToString();
                            Mcontext.Response.Write(re);
                        }
                        catch (Exception ex)
                        {
                            LogHelper.LogError("spui_sel", ex);
                            string re = "";
                            StringBuilder jsonStr = new StringBuilder();
                            jsonStr.Append("{\"sEcho\":\"");
                            jsonStr.Append(GetParam("sEcho"));
                            jsonStr.Append("\",\"iTotalRecords\":\"");
                            jsonStr.Append(0);
                            jsonStr.Append("\",\"iTotalDisplayRecords\":\"");
                            jsonStr.Append(0);
                            jsonStr.Append("\",\"data\":");

                            jsonStr.Append("[{\"id\":\"处理异常\"}]");
                            jsonStr.Append("}");

                            re = jsonStr.ToString();
                            Mcontext.Response.Write(re);
                            //Mcontext.Response.Write(JsonControl.AjaxJsonResultGridError(JsonControl.Error, ex.Message));
                        }

                        break;
                    }
                #endregion

         
                #region post update
                case JsonControl.Update:

                    try
                    {
                        if (string.IsNullOrEmpty(GetParam("id")))
                        {
                            throw new Exception("主键值缺失！");
                        }
                        if (string.IsNullOrEmpty(GetParam("tablemidname")))
                        {
                            throw new Exception("主键没指定！");
                        }

                        string erinfo = "";
                        HttpRequest Request = Mcontext.Request;
                        Hashtable allinfo = new Hashtable();
                        for (int i = 0; i < Request.Form.Count; i++)
                        {
                            allinfo.Add(Request.Form.Keys[i].ToString(), ObjIUD.sqlfieldc(Request.Form[i].ToString()));
                        }
                        Bs_Check.ywcheckonly(GetParam("ywcheckonly"), allinfo, 0, Mcontext);
                        bool re = ObjIUD.updateInfo(allinfo, out erinfo);

                        if (re)
                        {
                            Mcontext.Response.Write(JsonControl.AjaxJsonResultNewUI("y", JsonControl.GetJsonStr("提交成功")));
                        }
                        else
                            Mcontext.Response.Write(JsonControl.AjaxJsonResultNewUI("n", JsonControl.GetJsonStr(erinfo)));

                    }
                    catch (Exception ex)
                    {
                        LogHelper.LogError("spui_" + callBackAction, ex);
                        Mcontext.Response.Write(JsonControl.AjaxJsonResultNewUI("n", JsonControl.GetJsonStr(ex.Message)));
                    }

                    break;
                #endregion
                #region doedit
                case "doedit":

                    try
                    {
                        string id = "";
                        id = GetParam("id");
                        if (string.IsNullOrEmpty(id))
                        {
                            throw new Exception("请先选择要修改的记录，主键缺失！");
                        }
                        string erinfo = "";
                        Hashtable allinfo = new Hashtable();
                        string tablename = GetParam("tablename");
                        string fnamevalue = GetParam("fnamevalue");
                        string tablemidname = GetParam("tablemidname");
                        allinfo.Add("tablename", tablename);
                        allinfo.Add("id", id);
                        allinfo.Add("tablemidname", tablemidname);
                        string[] nv = fnamevalue.Split('$');
                        foreach (var s in nv)
                        {
                            allinfo.Add("f" + s.Split('%')[0], s.Split('%')[1]);
                        }

                        bool re = ObjIUD.updateInfo(allinfo, out erinfo);

                        if (re)
                        {
                            Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Success, JsonControl.GetJsonStr("更新成功")));
                        }
                        else
                            Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Fail, JsonControl.GetJsonStr(erinfo)));
                    }
                    catch (Exception ex)
                    {
                        LogHelper.LogError("spui_" + callBackAction, ex);
                        Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Error, JsonControl.GetJsonStr(ex.Message)));
                    }

                    break;
                #endregion
                case JsonControl.Delete:

                    try
                    {
                        string erinfo = "";
                        HttpRequest Request = Mcontext.Request;
                        Hashtable allinfo = new Hashtable();
                        for (int i = 0; i < Request.QueryString.Count; i++)
                        {
                            allinfo.Add(Request.QueryString.Keys[i].ToString(), Request.QueryString[i].ToString());
                        }

                        bool re = ObjIUD.delInfo(allinfo, out erinfo);

                        if (re)
                        {
                            Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Success, JsonControl.GetJsonStr("删除成功")));
                        }
                        else
                            Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Fail, JsonControl.GetJsonStr(erinfo)));
                    }
                    catch (Exception ex)
                    {
                        LogHelper.LogError("spui_" + callBackAction, ex);
                        Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Error, JsonControl.GetJsonStr(ex.Message)));
                    }

                    break;
                case "SqlTableGet":
                    try
                    {
                        //目前只支持如下内容
                        //select[]table[]group[]having[]where[]order[]  
                        //hcaddhc 代表+
                        string sqlinfo = GetParam("sqlinfo");
                        sqlinfo = sqlinfo.Replace("hcaddhc", "+");
                        string select = gethcParmByName(sqlinfo, "select");
                        string table = gethcParmByName(sqlinfo, "table");
                        bool ishcchart = false;//图标的查询
                        if (table.StartsWith("hcchart-"))
                        {
                            table = table.Replace("hcchart-", "");
                            ishcchart = true;
                        }
                        string where = gethcParmByName(sqlinfo, "where");
                        string group = gethcParmByName(sqlinfo, "group");
                        string having = gethcParmByName(sqlinfo, "having");
                        string order = gethcParmByName(sqlinfo, "order");
                        string nostate = GetParam("nostate");
                        string sql = "select " + select + " from " + table +
                            (string.IsNullOrEmpty(where) ? "" : " where " + where) +
                            (string.IsNullOrEmpty(group) ? "" : " group by  " + group) +
                            (string.IsNullOrEmpty(having) ? "" : " having " + having) +
                            (string.IsNullOrEmpty(order) ? "" : " order by " + order);
                        DataTable dt = null;
                        changePpageParm(ref  sql);
                        using (dbsimple db = new dbsimple())
                        {
                            dt = db.Query(sql);
                        }
                        if (!ishcchart)
                        {
                            if (string.IsNullOrEmpty(nostate))
                            {
                                Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Success, JsonControl.GetJsonStr(dt)));
                            }
                            else
                            { Mcontext.Response.Write(JsonControl.GetJsonStr(dt)); }
                        }
                        else
                        {
                            Mcontext.Response.Write(JsonControl.GetJsonStrForChar(dt));
                        }

                    }
                    catch (Exception ex)
                    {
                        LogHelper.LogError("spui_" + callBackAction, ex);
                        Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Error, JsonControl.GetJsonStr(ex.Message)));
                    }
                    break;
                case "SqlTableByPost":
                    try
                    {
                        //目前只支持如下内容

                        string select = GetParam("fselect");
                        string table = GetParam("ftable");
                        string where = GetParam("fwhere");
                        string group = GetParam("fgroup");
                        string having = GetParam("fhaving");
                        string order = GetParam("forder");
                        string nostate = GetParam("fnostate");

                        string sql = "select " + select + " from " + table +
                            (string.IsNullOrEmpty(where) ? "" : " where " + where) +
                            (string.IsNullOrEmpty(group) ? "" : " group by  " + group) +
                            (string.IsNullOrEmpty(having) ? "" : " having " + having) +
                            (string.IsNullOrEmpty(order) ? "" : " order by " + order);
                        DataTable dt = null;
                        using (dbsimple db = new dbsimple())
                        {
                            dt = db.Query(sql);
                        }
                        //if (!ishcchart)
                        //{
                        if (string.IsNullOrEmpty(nostate))
                        {
                            Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Success, JsonControl.GetJsonStr(dt)));
                        }
                        else
                        { Mcontext.Response.Write(JsonControl.GetJsonStr(dt)); }
                        //}
                        //else
                        //{
                        //    Mcontext.Response.Write(JsonControl.GetJsonStrForChar(dt));
                        //}

                    }
                    catch (Exception ex)
                    {
                        LogHelper.LogError("spui_" + callBackAction, ex);
                        Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Error, JsonControl.GetJsonStr(ex.Message)));
                    }
                    break;
                case "getpageinfo":
                    try
                    {
                        //目前只支持如下内容
                        //select[]table[]group[]having[]where[]order[]  
                        //hcaddhc 代表+


                        string select = GetParam("select");
                        string table = GetParam("table");
                        string where = GetParam("where");
                        string group = GetParam("group");
                        string having = GetParam("having");
                        string order = GetParam("order");
                        string nostate = GetParam("nostate");
                        string subinfo = GetParam("subinfo");//子查询info
                        string subinfo2 = GetParam("subinfo2");//子查询info
                        //string sql = "select " + select + " from " + table +
                        //    (string.IsNullOrEmpty(where) ? "" : " where " + where) +
                        //    (string.IsNullOrEmpty(group) ? "" : " group by  " + group) +
                        //    (string.IsNullOrEmpty(having) ? "" : " having " + having) +
                        //    (string.IsNullOrEmpty(order) ? "" : " order by " + order);
                        DataTable dt = null;
                        //changePpageParm(ref  sql);
                        //using (dbsimple db = new dbsimple())
                        //{
                        //    dt = db.Query(sql);
                        //}
                        int totalCount = 0;


                        int ipage = int.Parse(GetParam("pagenow"));
                        int irows = int.Parse(GetParam("pagesize"));

                        using (dbsimple db = new dbsimple())
                        {
                            if (ipage != 0) dt = db.getReportPage(table, select, ipage, irows, where, string.IsNullOrEmpty(order) ? null : order, ref totalCount);
                            else
                            {
                                dt = db.getReportNoPage(table, select, where, string.IsNullOrEmpty(order) ? null : order);
                            }
                        }
                        //if (string.IsNullOrEmpty(nostate))
                        //{
                        if (ipage != 0)
                        {
                            string allpage = "0";

                            if (totalCount != 0) allpage = (((totalCount - 1) / irows) + 1).ToString();
                            Mcontext.Response.Write(JsonControl.AjaxJsonResult(allpage, JsonControl.GetJsonStr(dt, subinfo, subinfo2, GetParam("subinfo3"), GetParam("subinfo4"))));
                        }
                        else
                        { Mcontext.Response.Write(JsonControl.GetJsonStr(dt, subinfo, subinfo2)); }


                    }

                    catch (Exception ex)
                    {
                        LogHelper.LogError("spui_" + callBackAction, ex);
                        Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Error, JsonControl.GetJsonStr(ex.Message)));
                    }
                    break;
                case "getLogininfo"://获取登记信息 
                    {
                        LoginUser l = (LoginUser)Mcontext.Session["LoginUser"];
                        string[] name = new[] { "HCUid", "HCUname", "HCUtitle", "HCUorg", "HCUdep", "HCUorgtype", "HCUdepName", "HCUorgName", "HCUorgCode" };
                        string[] value = new[] { l.UserId, l.UserName, l.UserTitle, l.UserOrg, l.UserDep, l.BranchType, l.UserDepName, l.UserOrgName, l.OrgCode };
                        Mcontext.Response.Write(JsonControl.GetJsonStr(name, value));

                    }
                    break;
                case "GetHcDeList":
                    try
                    {
                        string info = "";
                        info = new HCSPDE().CreateDataGridColumnModel(GetParam("listmid"));
                        DataTable dt_de = new HCSPDE().GetDeBaseInfo(GetParam("hcdemid"));
                        string son1listmid = "";
                        if (dt_de != null && dt_de.Rows.Count > 0)
                        {
                            son1listmid = dt_de.Rows[0]["son1listmid"].ToString();
                        }
                        string message = "noson";

                        if (!string.IsNullOrEmpty(son1listmid.ToString()))
                        {
                            message = "hasson";
                        }
                        //  Mcontext.Response.Write(info);
                        if (message == "hasson")
                        {
                            string info1 = new HCSPDE().CreateDataGridColumnModel(son1listmid);
                            string re = JsonControl.GetJsonStrNoSE(new string[] { "message", "data", "data1", "son1name" }, new string[] { message, info, info1, dt_de.Rows[0]["son1name"].ToString() });
                            Mcontext.Response.Write(re);
                        }
                        else
                        {
                            Mcontext.Response.Write("{\"message\":\"" + message + "\",\"data\":\"" + info + "\"}");
                        }

                    }
                    catch (Exception ex)
                    {
                        LogHelper.LogError("spui_" + callBackAction, ex);
                        Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Error, JsonControl.GetJsonStr(ex.Message)));
                    }
                    break;
                case "GetTableObjINFO":
                    {

                        try
                        {
                            string sql = "select * from {0} where {1}='{2}' ";
                            string talbename = GetParam("talbename");
                            string midname = GetParam("midname");
                            string midvalue = GetParam("midvalue");
                            sql = string.Format(sql, talbename, midname, midvalue);
                            DataTable dt = null;
                            using (dbsimple db = new dbsimple())
                            {
                                dt = db.Query(sql);
                            }
                            string re = JsonControl.AjaxJsonResult(JsonControl.Success, JsonControl.GetJsonStr(dt));
                            Mcontext.Response.Write(re);
                        }
                        catch (Exception ex)
                        {
                            LogHelper.LogError("spui_" + callBackAction, ex);
                            Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Error, JsonControl.GetJsonStr(ex.Message)));
                        }

                        break;
                    }
                case "doProc":
                    {

                        try
                        {
                            string procName = GetParam("procName");

                            HttpRequest Request = Mcontext.Request;
                            Hashtable allinfo = new Hashtable();
                            for (int i = 0; i < Request.QueryString.Count; i++)
                            {
                                if (Request.QueryString.Keys[i].ToString().StartsWith("hcp"))
                                {
                                    allinfo.Add(Request.QueryString.Keys[i].ToString(), Request.QueryString[i].ToString());
                                }
                            }

                            bool dore = false;
                            string outinfo = "";
                            using (dbsimple db = new dbsimple())
                            { dore = db.doProc(procName, allinfo, out  outinfo); }

                            string re = JsonControl.AjaxJsonResult(JsonControl.Success, JsonControl.GetJsonStr(outinfo));
                            Mcontext.Response.Write(re);
                        }
                        catch (Exception ex)
                        {
                            LogHelper.LogError("spui_" + callBackAction, ex);
                            Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Error, JsonControl.GetJsonStr(ex.Message)));
                        }

                        break;
                    }
                case "seltree":
                    {
                        try
                        {
                            // int totalCount = 0;
                            string orderType = GetParam("order");
                            string sortfeild = GetParam("sort");
                            string page = GetParam("page");
                            int ipage = 0;
                            int irows = 100;
                            if (!string.IsNullOrEmpty(page))
                            {
                                ipage = int.Parse(GetParam("page"));
                                irows = int.Parse(GetParam("rows"));
                            }
                            string tableinfo = GetParam("tableinfo");
                            string refields = GetParam("refields");
                            string wheresp = GetParam("wheresp");
                            string sporderby = GetParam("sporderby");
                            string whereadd = "  1=1 ";
                            string queryParams = GetParam("queryParams");
                            if (!string.IsNullOrEmpty(wheresp))
                            { whereadd += wheresp; }
                            //查询条件
                            HttpRequest Request = Mcontext.Request;

                            for (int i = 0; i < Request.Form.Count; i++)
                            {
                                if (Request.Form.Keys[i].ToString().StartsWith("find") && Request.Form[i].ToString().Trim().Length > 0)
                                {
                                    whereadd += " and T." + Request.Form.Keys[i].ToString().Replace("find", "") + " like '%" + Request.Form[i].ToString() + "%'";
                                }
                            }
                            string sql = "SELECT " + refields + "  FROM  " + tableinfo + " where " + whereadd;
                            string re = GetObjTree(sql);
                            if (string.IsNullOrEmpty(re))
                            { re = "[]"; }
                            Mcontext.Response.Write(re);
                        }
                        catch (Exception ex)
                        {
                            LogHelper.LogError("spui_" + callBackAction, ex);
                            Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Error, JsonControl.GetJsonStr(ex.Message)));
                        }

                        break;
                    }
                case "getbuttonaccess":
                    {

                        try
                        {
                            string pagecode = GetParam("pagecode");
                            string userid = GetParam("userid");
                            DataTable dt;
                            using (dbsimple db = new dbsimple())
                            {
                                dt = db.Query(@"SELECT  [BtnID] as id
      ,[BtnIDHtml] as code
      ,[BtnText] as name
      ,[BtnIcon] as icon
      ,[BtnNo] as sort 
  FROM sysButton as T inner join dbo.sysTab as T1 on T.TabMenuId=T1.pkid and T1.description='" + pagecode + "' and T.BtnID in (select * from GetUserBtAccess('" + userid + "')) and T.BtnIcon != 'notoolbaraccess' order by T.BtnNo");
                            }
                            Mcontext.Response.Write(GetToolBar(dt, pagecode));
                        }
                        catch (Exception ex)
                        {
                            LogHelper.LogError("spui_" + callBackAction, ex);
                            Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Error, JsonControl.GetJsonStr(ex.Message)));
                        }

                        break;
                    }
                case "sysdogo":
                    {
                        string re = new HCSPDE().sysdogo(GetParam("info"));
                        Mcontext.Response.Write(re);
                        break;
                    }
                case "Export":
                    {

                        try
                        {
                            string sqlinfo = GetParam("sqlinfo");
                            sqlinfo = sqlinfo.Replace("hcaddhc", "+");
                            string select = gethcParmByName(sqlinfo, "select");
                            string table = gethcParmByName(sqlinfo, "table");
                            string where = gethcParmByName(sqlinfo, "where");
                            string group = gethcParmByName(sqlinfo, "group");
                            string having = gethcParmByName(sqlinfo, "having");
                            string order = gethcParmByName(sqlinfo, "order");
                            string nostate = GetParam("nostate");
                            string sql = "select " + select + " from " + table +
                                (string.IsNullOrEmpty(where) ? "" : " where " + where) +
                                (string.IsNullOrEmpty(group) ? "" : " group by  " + group) +
                                (string.IsNullOrEmpty(having) ? "" : " having " + having) +
                                (string.IsNullOrEmpty(order) ? "" : " order by " + order);
                            DataTable dt = null;
                            changePpageParm(ref  sql);
                            using (dbsimple db = new dbsimple())
                            {
                                dt = db.Query(sql);
                            }
                            ExcelInOut.ExportDataTableToExcel(dt, HttpUtility.UrlEncode(DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls", System.Text.Encoding.UTF8), "数据");
                        }
                        catch (Exception ex)
                        {
                            LogHelper.LogError("spui_" + callBackAction, ex);
                            Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Error, JsonControl.GetJsonStr(ex.Message)));
                        }

                        break;
                    }
                case "Import":
                    try
                    {
                        string dfdfd = GetParam("impspfv");


                        if (context.Request.Files.Count < 1)
                            throw new ArgumentException("服务器没有找到上传文件！");

                        System.IO.Stream impFile = Mcontext.Request.Files["importFile"].InputStream;
                        string info = "";
                        DataTable dt = ExcelInOut.GetTable(impFile);
                        ObjIUD.importTable(dt, GetParam("imptablename"), GetParam("impspfv"), GetParam("improwstart"), GetParam("impcellstart"), GetParam("impfield"), out info);
                        //执行导入
                        Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Success, JsonControl.GetJsonStr("导入成功" + info)));
                    }
                    catch (Exception ex)
                    {
                        LogHelper.LogError("spui_" + callBackAction, ex);
                        Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Error, JsonControl.GetJsonStr(ex.Message)));
                    }

                    break;
                #region 工作流相关
                case "selhf":
                    try
                    {
                        int totalCount = 0;
                        string orderType = GetParam("order");
                        string sortfeild = GetParam("sort");
                        string page = GetParam("start");
                        //工作流业务
                        string wycode = GetParam("wycode");
                        int ipage = 0;
                        int irows = 100;
                        if (!string.IsNullOrEmpty(page))
                        {
                            irows = int.Parse(GetParam("length"));
                            ipage = int.Parse(GetParam("start"));
                            ipage = (ipage) / irows + 1;
                        }
                        string tableinfo = GetParam("tableinfo");
                        string refields = GetParam("refields");
                        //string dfdf = GetParam("finddename");
                        string wheresp = GetParam("wheresp");
                        string sporderby = GetParam("sporderby");
                        string whereadd = "  1=1 ";
                        if (!string.IsNullOrEmpty(wheresp))
                        { whereadd += wheresp; }
                        //查询条件
                        HttpRequest Request = Mcontext.Request;
                        string fieldinfo = "";
                        string fieldvalue = "";
                        for (int i = 0; i < Request.Form.Count; i++)
                        {

                            if (Request.Form.Keys[i].ToString().StartsWith("find") && Request.Form[i].ToString().Trim().Length > 0)
                            {
                                fieldinfo = Request.Form.Keys[i].ToString().Replace("find", "");
                                fieldvalue = ObjIUD.sqlfieldc(Request.Form[i].ToString());
                                if (fieldinfo.EndsWith("_l"))
                                { whereadd += " and " + fieldinfo.Replace("_l", "") + " like '%" + fieldvalue + "%'"; }
                                else if (fieldinfo.EndsWith("_d"))
                                { whereadd += " and " + fieldinfo.Replace("_d", "") + " = '" + fieldvalue + "'"; }
                                else if (fieldinfo.EndsWith("_time"))
                                {
                                    whereadd += " and " + fieldinfo.Replace("_time", "") + " = '" + fieldvalue + "'";
                                }
                                else if (fieldinfo.EndsWith("_times"))
                                {
                                    whereadd += " and " + fieldinfo.Replace("_times", "") + " >= '" + fieldvalue + "'";
                                }
                                else if (fieldinfo.EndsWith("_timee"))
                                {
                                    whereadd += " and " + fieldinfo.Replace("_timee", "") + " <= '" + fieldvalue + "'";
                                }
                                else
                                {
                                    whereadd += " and " + fieldinfo + " like '%" + fieldvalue + "%'";
                                }

                            }
                        }

                        //{
                        //    string oc = GetParam("order[0][column]");
                        //    string od = GetParam("order[0][dir]");
                        //    if (!string.IsNullOrEmpty(oc))
                        //    {
                        //        if (!string.IsNullOrEmpty(GetParam("columns[" + oc + "][data]")))
                        //        {
                        //            sporderby = " " + GetParam("columns[" + oc + "][data]") + " " + (string.IsNullOrEmpty(od) ? "" : od);
                        //        }
                        //    }
                        //}

                        {
                            string oc = GetParam("order[0][column]");
                            string od = GetParam("order[0][dir]");
                            if (!string.IsNullOrEmpty(oc))
                            {
                                if (!string.IsNullOrEmpty(GetParam("columns[" + oc + "][data]")))
                                {
                                    if (string.IsNullOrEmpty(sporderby))
                                    {
                                        sporderby = " " + GetParam("columns[" + oc + "][data]") + " " + (string.IsNullOrEmpty(od) ? "" : od);
                                    }
                                    else
                                    {
                                        sporderby = " " + sporderby + "," + GetParam("columns[" + oc + "][data]") + " " + (string.IsNullOrEmpty(od) ? "" : od);
                                    }
                                }
                            }
                        }

                        LoginUser l = (LoginUser)Mcontext.Session["LoginUser"];


                        DataTable dt = null;
                        using (dbsimple db = new dbsimple())
                        {
                            if (ipage != 0) dt = db.getReportPagehf(l, wycode, tableinfo, refields, ipage, irows, whereadd, string.IsNullOrEmpty(sporderby) ? null : sporderby, out totalCount);
                            else
                            {
                                dt = db.getReportNoPagehf(l, wycode, tableinfo, refields, whereadd, string.IsNullOrEmpty(sporderby) ? null : sporderby);
                            }
                        }
                        string re = "";
                        StringBuilder jsonStr = new StringBuilder();
                        jsonStr.Append("{\"sEcho\":\"");
                        jsonStr.Append(GetParam("sEcho"));
                        jsonStr.Append("\",\"iTotalRecords\":\"");
                        jsonStr.Append(totalCount);
                        jsonStr.Append("\",\"iTotalDisplayRecords\":\"");
                        jsonStr.Append(totalCount);
                        jsonStr.Append("\",\"data\":");
                        if (dt.Rows.Count == 0)
                            jsonStr.Append("[]");
                        else
                            jsonStr.Append(JsonControl.GetJsonStr(dt));
                        jsonStr.Append("}");

                        re = jsonStr.ToString();
                        Mcontext.Response.Write(re);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.LogError("spui_" + callBackAction, ex);
                        string re = "";
                        StringBuilder jsonStr = new StringBuilder();
                        jsonStr.Append("{\"sEcho\":\"");
                        jsonStr.Append(GetParam("sEcho"));
                        jsonStr.Append("\",\"iTotalRecords\":\"");
                        jsonStr.Append(0);
                        jsonStr.Append("\",\"iTotalDisplayRecords\":\"");
                        jsonStr.Append(0);
                        jsonStr.Append("\",\"data\":");

                        jsonStr.Append("[{\"id\":\"处理异常\"}]");
                        jsonStr.Append("}");

                        re = jsonStr.ToString();
                        Mcontext.Response.Write(re);
                        //Mcontext.Response.Write(JsonControl.AjaxJsonResultGridError(JsonControl.Error, ex.Message));
                    }

                    break;

                case "hcrf_getyw"://查找工作流业务记录by ywcode and id
                    {

                        try
                        {
                            //工作流业务代码
                            string wycode = GetParam("wycode");
                            //查询的内容：为空( or 1)代表只返回工作流程信息     2返回表所有+工作流信息
                            string infotype = GetParam("infotype");
                            //string sql = "select * from {0} where {1}='{2}' ";
                            //业务主表
                            //   string talbename = GetParam("talbename");

                            //string midname = GetParam("midname");
                            //业务ID

                            string midvalue = GetParam("midvalue");
                            //sql = string.Format(sql, talbename, midname, midvalue);
                            DataTable dt = null;
                            using (dbsimple db = new dbsimple())
                            {
                                if (string.IsNullOrEmpty(infotype) || infotype == "1")
                                {
                                    dt = db.Query("select 1 as hasstart,view_hc_wfruning.* from view_hc_wfruning where fruntype='" + wycode + "' and frunywid='" + midvalue + "'");
                                    //如果没有，即没发起
                                    if (dt == null || dt.Rows.Count == 0) dt = db.Query("select 0 as hasstart,view_hc_wfdeall.* from view_hc_wfdeall where fruntype='" + wycode + "' and hcrntype='发起'");
                                }
                                else
                                {
                                    //没处理，主表信息
                                    dt = db.Query("select 1 as hasstart,view_hc_wfruning.* from view_hc_wfruning where fruntype='" + wycode + "' and frunywid='" + midvalue + "'");
                                    //如果没有，即没发起
                                    if (dt == null || dt.Rows.Count == 0) dt = db.Query("select 0 as hasstart,view_hc_wfdeall.* from view_hc_wfdeall where fruntype='" + wycode + "' and hcrntype='发起'");
                                    //dt = db.Query("select 1 as hasstart,*  from " + talbename + "  as t inner join  view_hc_wfruning as t1  on t.id = t1.frunywid   and  t1.fruntype='" + wycode + "' and t1.frunywid=" + midvalue);
                                    ////如果没有，即没发起
                                    //if (dt == null || dt.Rows.Count == 0) dt = db.Query("select  0 as hasstart,* from view_hc_wfdeall where fruntype='" + wycode + "' and hcrntype='发起'");

                                }
                            }
                            string re = JsonControl.AjaxJsonResult(JsonControl.Success, JsonControl.GetJsonStr(dt));
                            Mcontext.Response.Write(re);
                        }
                        catch (Exception ex)
                        {
                            LogHelper.LogError("spui_" + callBackAction, ex);
                            Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Error, JsonControl.GetJsonStr(ex.Message)));
                        }

                        break;
                    }
                case "hcrf_start":
                    try
                    {
                        string erinfo = "";
                        LoginUser l = (LoginUser)Mcontext.Session["LoginUser"];
                        Hashtable allinfo = new Hashtable();
                        allinfo.Add("tablename", "hcr_w_runuser");
                        allinfo.Add("fruntype", GetParam("fruntype"));
                        allinfo.Add("frunywid", GetParam("frunywid"));
                        allinfo.Add("fhcrdostate", GetParam("fhcrdostate"));
                        allinfo.Add("fdesc", GetParam("fdesc"));
                        allinfo.Add("fdoend", "通过");
                        allinfo.Add("fsubtime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        allinfo.Add("fdodep", l.UserDep);
                        allinfo.Add("fdoorg", l.UserOrg);
                        allinfo.Add("fdouser", l.UserId);
                        allinfo.Add("fdousername", l.UserName);
                        allinfo.Add("fdoutitle", l.UserTitle);
                        allinfo.Add("fruningdo", "待处理");
                        allinfo.Add("fnname", "发起业务");
                        allinfo.Add("fntype", "发起");
                        //查找业务的创建人员
                        string ywcreateuid = "";

                        using (dbsimple db = new dbsimple())
                        {
                            string tname = db.Query("select ywmaintable from hcr_w_wtoyw where ywcode='" + GetParam("fruntype") + "'").Rows[0][0].ToString();
                            ywcreateuid = db.Query("select fhcrwfadduser from " + tname + " where id='" + GetParam("frunywid") + "'").Rows[0][0].ToString();
                        }

                        bool re = ObjIUD.insert(allinfo, out erinfo);
                        if (re)
                        {
                            new HCRainEF().hcrain_wf_start(ywcreateuid, l.UserId);
                            Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Success, JsonControl.GetJsonStr("发起成功")));
                        }
                        else
                            Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Fail, JsonControl.GetJsonStr(erinfo)));

                    }
                    catch (Exception ex)
                    {
                        LogHelper.LogError("spui_" + callBackAction, ex);
                        Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Error, JsonControl.GetJsonStr(ex.Message)));
                    }

                    break;
                case "hcrf_next":
                    try
                    {
                        string erinfo = "";
                        LoginUser l = (LoginUser)Mcontext.Session["LoginUser"];
                        Hashtable allinfo = new Hashtable();
                        allinfo.Add("tablename", "hcr_w_runuser");
                        allinfo.Add("fruntype", GetParam("fruntype"));
                        allinfo.Add("frunywid", GetParam("frunywid"));
                        allinfo.Add("fhcrdostate", GetParam("fhcrdostate"));
                        allinfo.Add("fdesc", GetParam("fdesc"));
                        allinfo.Add("fdoend", GetParam("fdoend"));
                        allinfo.Add("fsubtime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        allinfo.Add("fdodep", l.UserDep);
                        allinfo.Add("fdoorg", l.UserOrg);
                        allinfo.Add("fdouser", l.UserId);
                        allinfo.Add("fdoutitle", l.UserTitle);
                        allinfo.Add("fdousername", l.UserName);

                        allinfo.Add("fruningdo", "待处理");
                        allinfo.Add("frunid", GetParam("frunid"));
                        allinfo.Add("fdeid", GetParam("fdeid"));
                        allinfo.Add("fnname", GetParam("fnname"));
                        allinfo.Add("fntype", GetParam("fntype"));
                        bool re = ObjIUD.insert(allinfo, out erinfo);
                        if (re)
                        {
                            new HCRainEF().hcrain_wf_next();
                            Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Success, JsonControl.GetJsonStr("提交成功")));
                        }
                        else
                            Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Fail, JsonControl.GetJsonStr(erinfo)));

                    }
                    catch (Exception ex)
                    {
                        LogHelper.LogError("spui_" + callBackAction, ex);
                        Mcontext.Response.Write(JsonControl.AjaxJsonResult(JsonControl.Error, JsonControl.GetJsonStr(ex.Message)));
                    }
                    break;

                #endregion
                default:
                    {
                        Mcontext.Response.Write(JsonControl.AjaxJsonResultNewUI("n", JsonControl.GetJsonStr("系统不知道，这个请求，来自于哪里！或者数据走掉了？")));
                        break;
                    }
            }
        }


        public void changePpageParm(ref  string info)
        {
            info = info.Replace("hcdhc", "'");
        }

        /// <summary>
        /// 获取字段必要包含 ID   ShowInfo  ShowInfo2 ParentId
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public string GetObjTree(string sql)
        {
            DataTable dt = null;
            using (dbsimple db = new dbsimple())
            {
                dt = db.Query(sql);
            }
            System.Text.StringBuilder str = new System.Text.StringBuilder();
            string sstring;
            if (dt.Rows.Count > 0)
            {
                str.Append(RecursionSP(dt, 0, out sstring));
                str = str.Remove(str.Length - 2, 2);
            }
            return str.ToString();
        }
        // 获取字段必要包含 ID   ShowInfo ShowInfo2 ParentId
        private string RecursionSP(DataTable dt, object parentId, out string sondatastring)
        {
            System.Text.StringBuilder sbJson = new System.Text.StringBuilder();
            DataRow[] rows = dt.Select("ParentId = " + parentId);
            sondatastring = "";
            string iconCls = "";
            if (rows.Length > 0)
            {
                sbJson.Append("[");
                for (int i = 0; i < rows.Length; i++)
                {
                    if (i == 0) sondatastring = rows[i]["Id"].ToString(); else sondatastring += "," + rows[i]["Id"].ToString();
                    string thissonstring = "";
                    string childString = RecursionSP(dt, rows[i]["id"], out thissonstring);
                    int i_icon = dt.Columns.IndexOf("iconCls");
                    if (i_icon > 0)
                    {
                        iconCls = rows[i]["iconCls"].ToString();
                    }
                    if (!string.IsNullOrEmpty(childString))
                    {
                        //comboTree必须设置【id】和【text】，一个是id一个是显示值
                        sbJson.Append("{\"id\":\"" + rows[i]["Id"].ToString() + "\",\"iconCls\":\"" + iconCls + "\",\"sondata\":\"" + thissonstring + "\",\"ParentId\":\"" + rows[i]["ParentId"].ToString() + "\",\"ShowInfo2\":\"" + rows[i]["ShowInfo2"].ToString() + "\",\"text\":\"" + rows[i]["ShowInfo"].ToString() + "\",\"children\":");
                        sbJson.Append(childString);
                    }
                    else
                        sbJson.Append("{\"id\":\"" + rows[i]["Id"].ToString() + "\",\"iconCls\":\"" + iconCls + "\",\"sondata\":\"" + thissonstring + "\",\"ParentId\":\"" + rows[i]["ParentId"].ToString() + "\",\"ShowInfo2\":\"" + rows[i]["ShowInfo2"].ToString() + "\",\"text\":\"" + rows[i]["ShowInfo"].ToString() + "\"},");
                }
                sbJson.Remove(sbJson.Length - 1, 1);
                sbJson.Append("]},");
            }
            return sbJson.ToString();
        }
        /// <summary>
        /// 输出操作按钮
        /// </summary>
        /// <param name="dt">根据用户id和菜单标识码得到的用户可以操作的此菜单下的按钮集合</param>
        /// <param name="pageName">当前页面名称，方便拼接js函数名</param>
        public static string GetToolBar(DataTable dt, string pageName)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("{\"toolbar\":[");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                sb.Append("{\"text\": \"" + dt.Rows[i]["Name"] + "\",\"iconCls\":\"" + dt.Rows[i]["Icon"] + "\",\"handler\":\"" + dt.Rows[i]["Code"].ToString() + "();\"},");

            }

            bool flag = true;   //是否有浏览权限
            DataRow[] row = dt.Select("code = 'browser'");
            if (row.Length == 0)  //没有浏览权限
            {
                flag = false;
                if (dt.Rows.Count > 0)
                    sb.Remove(sb.Length - 1, 1);
            }
            else
            {
                if (dt.Rows.Count > 1)
                    sb.Remove(sb.Length - 1, 1);
            }
            sb.Append("],\"success\":true,");
            if (flag)
                sb.Append("\"browser\":true}");
            else
                sb.Append("\"browser\":false}");

            return sb.ToString();
        }

        public string gethcParmByName(string parminfo, string name)
        {
            //select[]table[]group[]having[]where[]order[]  

            string re = "";
            int index = parminfo.IndexOf(name + "[");
            if (index >= 0)
            {
                parminfo = parminfo.Substring(index + name.Length + 1);
                parminfo = parminfo.Substring(0, parminfo.IndexOf("]"));
                re = parminfo;
            }
            return re;

        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }










    }
}